from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.exc import OperationalError
import time
from urllib.parse import quote_plus

# 创建数据库实例
db = SQLAlchemy()

def init_db(app: Flask):
    """初始化数据库连接"""
    max_retries = 5
    retry_count = 0
    
    while retry_count < max_retries:
        try:
            # 获取数据库URI并确保正确编码
            db_uri = app.config['SQLALCHEMY_DATABASE_URI']
            
            # 测试数据库连接
            engine = create_engine(db_uri, encoding='utf8', client_encoding='utf8')
            with engine.connect() as connection:
                # 验证连接是否成功
                connection.execute("SELECT 1")
            print("数据库连接成功！")
            
            # 初始化SQLAlchemy
            db.init_app(app)
            return True
            
        except OperationalError as e:
            retry_count += 1
            if retry_count == max_retries:
                print(f"无法连接到数据库，错误信息：{str(e)}")
                raise e
            print(f"数据库连接失败，{max_retries - retry_count}秒后重试...")
            time.sleep(1)
            
def close_db(e=None):
    """关闭数据库连接"""
    db.session.remove()
